let app = getApp();
const { getOpenID, getUserInfoWidthCredentials } = require('../../utils/ws/wsxcx-opendata-sdk');
Component({
  properties: {
    isShow: {
      type: Boolean,
      value: false,
    },
    showCancel: {
      type: Boolean,
      value: true,
    },
    useAuthPage: {
      type: Boolean,
      value: false,
      observer(newVal) {
        if (newVal === true) {
          app.util.navigateTo(this.data.authPath);
        }
      },
    },
    needUserInfo: {
      type: Boolean,
      value: false,
    },

    needEncryptedData: {
      type: Boolean,
      value: false,
    },

    needUserInfoCache: {
      type: Boolean,
      value: false,
    },
  },

  data: {
    platform: 'android',
    url: 'auth/session/phoneinfo',
    authPath: '/common/page/auth/auth',
    moduleName: '',
    modulesNeedCatch: ['ws_micro_company', 'ws_house', 'ws_micro_cms', 'ws_micro_live'],
  },

  attached() {
    const that = this;
    wx.getSystemInfo({
      success: res => {
        res && that.setData({ platform: res.platform });
      },
    });
    this.setData({ moduleName: app.modules || '' });
    wx.getStorageSync('needAuthLoginOnPageLoad') !== false && this.getConfig().then((res) => {
      res && that.setData({
        isShow: true,
      });
    });
  },

  methods: {
    getConfig() {
      return new Promise((resolve) => {
        getOpenID({ mode: 1 }).then(() => {
          app.util.request({
            url: 'auth/session/copyright',
            method: 'get',
            success: res => {
              let response = res.data.data || '';
              if (res.statusCode === 200 && response) {
                Number(response.wxapp_accredit) === 1 && app.util.navigateTo(this.data.authPath);  // 网页形式的授权
                Number(response.wxapp_accredit) === 2 && resolve(!!Number(response.wxapp_accredit));
                !Number(response.wxapp_accredit) && wx.setStorageSync('needAuthLoginOnPageLoad', false);
              }
            },
          });
        });
      });
    },

    getUserInfo(e) {
      wx.showLoading();
      const that = this;
      let { moduleName, needUserInfo, modulesNeedCatch, needUserInfoCache, needEncryptedData } = this.data;

      if (e.detail.errMsg === 'getUserInfo:ok') {
        let userInfo = moduleName === 'ws_micro_shop' ? (wx.getStorageSync('user_info') || {}) : e.detail;

        moduleName === 'ws_micro_shop' && this.shopModuleRequest(e).then(res => {
          // 兼容商城模块
          userInfo.unionid = res.data.unionid || '';
          userInfo.info = 1;
          wx.setStorageSync('user_info', userInfo);
          wx.setStorageSync('cancel', true);
          wx.setStorageSync('needAuthLoginOnPageLoad', false);
          let eventData = { isAuthorization: true, hasWxInfo: true };
          needUserInfo && (eventData.userInfo = res.data);
          needEncryptedData && (eventData.encryptedData = { encryptedData: e.detail.encryptedData, iv: e.detail.iv });
          that.triggerEvent('getUserInfo', eventData);
        }).then(() => { wx.hideLoading() });

        moduleName === 'ws_micro_shop' || getUserInfoWidthCredentials(e).then(res => {
          // 签名错误或返回空数组
          if (Number(res.data.errno) === 1) {
            that.authFailed(that);
            return;
          } else if (Number(res.data.errno === 0) && res.data.data instanceof Array && res.data.data.length === 0) {
            that.authFailed(that);
            return;
          }

          userInfo.uid = res.data.data.uid || '';
          let eventData = { isAuthorization: true, hasWxInfo: true };
          needUserInfo && (eventData.userInfo = res.data.data);
          needEncryptedData && (eventData.encryptedData = { encryptedData: e.detail.encryptedData, iv: e.detail.iv });
          that.triggerEvent('isAuthorization', eventData);
          that.triggerEvent('getUserInfo', eventData);
          (modulesNeedCatch.includes(moduleName) || needUserInfoCache) && wx.setStorageSync('_wxInfo', userInfo);  // 缓存用户信息
          wx.setStorageSync('needAuthLoginOnPageLoad', false);
        }, () => {
          that.authFailed(that);
        }).then(() => {
          wx.hideLoading();
        });
      } else {
        that.authFailed(that);
      }
      this.setData({ isShow: false });
    },

    authFailed(that) {
      that.triggerEvent('isAuthorization', { isAuthorization: false });
      that.triggerEvent('getUserInfo', { hasWxInfo: false });
      wx.hideLoading();
    },

    shopModuleRequest(e) {
      return new Promise((resolve, reject) => {
        app.ws_micro_shoplogin(1).then(() => {
          const systemInfo = wx.getSystemInfoSync();
          app.ws_micro_shoprequest({
            url: app.api.passport.info,
            data: {
              user_info: JSON.stringify(e.detail.userInfo),
              encrypted_data: e.detail.encryptedData,
              iv: e.detail.iv,
              brand: systemInfo.brand,
              model: systemInfo.model,
            },
            method: 'POST',
            success: res => { Number(res.code) === 0 && resolve(res) },
            fail: () => { wx.hideLoading() },
          });
        });
      });
    },

    togglePop() {
      this.setData({ isShow: !this.data.isShow });
      this.authFailed(this);
    },
  },
});
